package com.yc.mvc.web;

import com.yc.mvc.bean.User;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;

@Controller
// 监视 Model 中的指定属性, 如果出现, 那么就将其存入会话
//  指定属性 : 1 指定名称, 2. 指定类型
@SessionAttributes(value = "loginedUser", types = User.class)
public class LoginAction {

    @GetMapping(value = "login", produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8")
    @ResponseBody
    public String login(String name, String pwd, HttpSession session) {
        if ("yc".equals(name) && "123".equals(pwd)) {
            session.setAttribute("loginedUser", "yc");
            return "登录成功!";
        } else {
            return "登录失败!";
        }
    }

    // SessionAttribute 用户读取会话中的指定属性值, 注入到方法参数种, 使用参数名映射规则
    @ResponseBody
    @GetMapping(path = "getLoginedUser", produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8")
    public String getLoginedUser(@SessionAttribute(required = false) String loginedUser) {
        if (loginedUser == null) {
            return "请求先登录系统";
        } else {
            return "当前登录的用户是: " + loginedUser;
        }
    }

    @GetMapping("login1")
    public String login1(String name, String pwd, Model model) {
        if ("yc".equals(name) && "123".equals(pwd)) {
            model.addAttribute("loginedUser", "yc");
            return "redirect:index.html";
        } else {
            return "redirect:rm.html";
        }
    }

    @GetMapping("logout")
    public String logout(HttpSession session, SessionStatus sessionStatus){
        // 注销会话
        //session.invalidate();
        // 终止会话
        sessionStatus.setComplete();
        return "redirect:index.html";
    }

}
